// Package job
// Created by GoLand
// @User: lenora
// @Date: 2024/8/7
// @Time: 15:56

package job

import (
	"camp/microbook/pkg/logger"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/robfig/cron/v3"
	"strconv"
	"time"
)

type cronJobBuilder struct {
	l      logger.Logger
	vector *prometheus.SummaryVec
}

func NewCronJobBuilder(l logger.Logger, opts prometheus.SummaryOpts) *cronJobBuilder {
	vector := prometheus.NewSummaryVec(opts, []string{"job_name", "status"})
	prometheus.MustRegister(vector)
	return &cronJobBuilder{l: l, vector: vector}
}

func (j *cronJobBuilder) Build(job Job) cron.Job {
	name := job.Name()
	return cron.FuncJob(func() {
		var err error
		start := time.Now()
		//prometheus.MustRegister(j.vector)
		defer func() {
			dur := time.Since(start)
			j.vector.
				WithLabelValues(name, strconv.FormatBool(err == nil)).
				Observe(float64(dur.Milliseconds()))
		}()
		err = job.Run()
		if err != nil {
			j.l.Error("job execute failed",
				logger.String("name", name),
				logger.Error(err),
			)
		}
	})
}
